package com.tembli.skills.dao.hibernate;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.tembli.skills.dao.ProjectDAO;
import com.tembli.skills.model.Project;

/**
 * This class interacts with Spring and Hibernate to save and retrieve User
 * objects.
 * 
 */
@Repository(value = "projectDao")
public class ProjectDAOHibernate implements ProjectDAO {
	HibernateTemplate hibernateTemplate;
	Log logger = LogFactory.getLog(ProjectDAOHibernate.class);

	@Autowired
	public ProjectDAOHibernate(final SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	public List getProjects() {
		return hibernateTemplate.find("from Project");
	}

	public Project getProject(final Long id) {
		Project project = (Project) hibernateTemplate.get(Project.class, id);
		if (project == null)
			throw new ObjectRetrievalFailureException(Project.class, id);
		return project;
	}

	public void saveProject(final Project project) {
		hibernateTemplate.saveOrUpdate(project);

		if (logger.isDebugEnabled()) {
			logger.debug("projectId set to: " + project.getId());
		}
	}

	public void removeProject(final Long id) {
		hibernateTemplate.delete(getProject(id));
	}
}
